from django.shortcuts import render, redirect, get_object_or_404, Http404
from . import models, forms


def is_login(func):
	def _(request, *args, **kwargs):
		if request.user.is_authenticated:
			return func(request, *args, **kwargs)
		else:
			return render(request, 'did_not_login.html')
	
	return _


@is_login
def index(request):
	li = []
	context = {'chatgroups': li}
	for i in models.Member.objects.filter(owner=request.user).all():
		li.append(i.group)
	return render(request, 'index.html', context)


@is_login
def chatgroup(request, group_id):
	group = get_object_or_404(models.ChatGroup, id=group_id)
	reports = group.report_set.all()[::-1]
	form = forms.ReportForm()
	context = {
		'group': group,
		'reports': reports,
		'form': form
	}
	return render(request, 'chatgroup.html', context)


@is_login
def send_message(request, group_id):
	form = forms.ReportForm(data=request.POST)
	group = get_object_or_404(models.ChatGroup, id=group_id)
	r = form.save(commit=False)
	r.chatgroup = group
	r.username = request.user.username
	r.save()
	return redirect(f'/chatgroup/{group_id}')


@is_login
def join_group(request, group_id):
	if request.method != 'POST':
		group = get_object_or_404(models.ChatGroup, id=group_id)
		password = ''
	else:
		group = get_object_or_404(models.ChatGroup, id=group_id)
		password = request.POST.get('password', None)
		if request.POST.get('password', None) == str(group.password):
			f = forms.MemberFrom()
			member = f.save(commit=False)
			member.owner = request.user
			member.group = group
			member.save()
			return redirect('chat:index')
	
	context = {'password': password, 'group': group}
	return render(request, 'join_group.html', context)


@is_login
def create_group(request):
	if request.method != 'POST':
		form = forms.ChatGroupForm()
	else:
		form = forms.ChatGroupForm(data=request.POST)
		if form.is_valid():
			g = form.save()
			m = models.Member()
			m.group = g
			m.owner = request.user
			m.save()
			return redirect('chat:index')
	context = {'form': form}
	return render(request, 'create_group.html', context)


@is_login
def delete_member(request, group_id):
	group = get_object_or_404(models.ChatGroup, id=group_id)
	members = group.member_set.filter(owner=request.user).all()
	members_length = len(members)
	if members_length == 1:
		members[0].delete()
		return redirect(f"chat:index")
	elif members_length == 0:
		raise Http404
	else:
		for i in members[1:]:
			i.delete()
		return redirect(f"chat:index")


def search_group(request):
	return render(request, 'search.html')
